package com.sa.token.oauth2.demo.satokenoauth2demo.controller;

import cn.dev33.satoken.oauth2.logic.SaOAuth2Consts;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
public class AuthorizationCodeController {

    @RequestMapping("/authorizationCode/checkToken")
    public String checkToken(HttpServletRequest req) {
        String clientId = req.getParameter(SaOAuth2Consts.Param.client_id);
        String clientSecret = req.getParameter(SaOAuth2Consts.Param.client_secret);
        String accessToken = req.getParameter(SaOAuth2Consts.Param.access_token);
        String scope = req.getParameter(SaOAuth2Consts.Param.scope);

        //校验accessToken 是否有效
        SaOAuth2Util.checkAccessTokenParam(clientId, clientSecret, accessToken);

        //验证scope
        SaOAuth2Util.checkScope(accessToken, scope);

        //获取用户登录信息
        Object userInfo = this.getUserInfo(clientId, clientSecret, accessToken);
        if(Objects.isNull(userInfo)){
            return "授权码登录失败";
        }

        return "授权码登录的"+userInfo;
    }

    @RequestMapping("/authorizationCode/getUserInfo")
    public String getUserInfo(HttpServletRequest req) {
        String clientId = req.getParameter(SaOAuth2Consts.Param.client_id);
        String clientSecret = req.getParameter(SaOAuth2Consts.Param.client_secret);
        String accessToken = req.getParameter(SaOAuth2Consts.Param.access_token);

        //校验accessToken 是否有效
        SaOAuth2Util.checkAccessTokenParam(clientId, clientSecret, accessToken);

        //获取用户登录信息
        Object loginId = SaOAuth2Util.getLoginIdByAccessToken(accessToken);
        Object userInfo = StpUtil.getSessionByLoginId(loginId).get("userInfo");

        return "授权码登录的"+userInfo;
    }

    private Object getUserInfo(String clientId, String clientSecret, String accessToken){
        //校验accessToken 是否有效
        SaOAuth2Util.checkAccessTokenParam(clientId, clientSecret, accessToken);

        //获取用户登录信息
        Object loginId = SaOAuth2Util.getLoginIdByAccessToken(accessToken);
        return StpUtil.getSessionByLoginId(loginId).get("userInfo");
    }

}
